package com.xsq.audio;

import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;

import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.MediaMetadata;
import com.google.android.exoplayer2.util.MimeTypes;
import com.xsq.audio.player.utils.SPUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 保存在内存的音频列表
 * Created by Shiquan.Xiao on 2023/3/29.
 */
public class AudioDataSource {

    /**
     * 缓存专辑音频列表的键
     */
    public static final String BROWSER_ROOT_ID = "/";
    public static final String BROWSER_CONTROLLER_CLOSE = "browser_controller_close";
    public static final String EXTRA_ROOT_ID_DATA = "extra_root_id_data";
    public static final String EXTRA_AUDIO_ITEM_INDEX = "extra_current_audio_item_index";
    public static final String EXTRA_AUDIO_PLAY_DATA = "extra_current_audio_play_data";
    public static final int RESULT_CODE_AUDIO_ITEM_INDEX = 1001;
    //歌曲切换
    public static final int RESULT_CODE_AUDIO_PLAY_CHANGE = 1002;

    private final Map<String, List<MediaMetadataCompat>> rootIdDataMap = new HashMap<>();

    public AudioDataSource() {
    }

    public List<MediaMetadataCompat> getDataForRootId(String rootId) {
        if (!rootIdDataMap.isEmpty()) {
            return rootIdDataMap.get(rootId);
        }
        return null;
    }

    public void putToRootData(String rootId, List<AudioItemData> audioItemList) {
        List<MediaMetadataCompat> metadataList = null;
        if (!rootIdDataMap.isEmpty()) {
            metadataList = rootIdDataMap.get(rootId);
        }
        if (metadataList != null) {
            metadataList.clear();
        }
        metadataList = convertToAudioData(audioItemList);
        rootIdDataMap.put(rootId, metadataList);
    }

    /**
     * 清除缓存
     */
    public void release() {
        rootIdDataMap.clear();
    }

    public static List<MediaMetadataCompat> convertToAudioData(List<AudioItemData> list) {
        if (list != null && !list.isEmpty()) {
            List<MediaMetadataCompat> audioList = new ArrayList<>();

            int size = list.size();
            for (int i = 0; i< size; i++) {
                audioList.add(convertAudioToMetaData(list.get(i), i, size).build());
            }
            return audioList;
        }
        return null;
    }

    public static MediaMetadataCompat.Builder convertAudioToMetaData(AudioItemData data, int trackNumber, int trackCount) {
        MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder();
        //唯一音乐id
        builder.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, data.getAudioId());
        //标题
        builder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, data.getName());
        //音乐播放源
        builder.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, data.getPlayUrl());
        //显示标题
        builder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, data.getSeries());
        //艺术家
        builder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST,"rs");
        //专辑
        builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, data.getCategory());
        //作曲家
        builder.putString(MediaMetadataCompat.METADATA_KEY_COMPOSER, "rs");
        //歌唱家
        builder.putString(MediaMetadataCompat.METADATA_KEY_WRITER, "rs");
        //专辑图片
        builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, "");
        //歌曲顺序序号
        builder.putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, trackNumber);
        //歌曲总数量
        builder.putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, trackCount);
        //持续时间
        builder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, 0);

        return builder;
    }

    public static List<MediaItem> convertDataToMediaItem(List<MediaMetadataCompat> list) {
        List<MediaItem> mediaItemList = new ArrayList<>();
        for (MediaMetadataCompat m: list) {
            String title = m.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
            String audioUri = m.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI);
            String displayTitle = m.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE);
            String artist = m.getString(MediaMetadataCompat.METADATA_KEY_ARTIST);
            String album = m.getString(MediaMetadataCompat.METADATA_KEY_ALBUM);
            String composer = m.getString(MediaMetadataCompat.METADATA_KEY_COMPOSER);
            String writer = m.getString(MediaMetadataCompat.METADATA_KEY_WRITER);
            String albumArtUri = m.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI);
            long duration = m.getLong(MediaMetadataCompat.METADATA_KEY_DURATION);
            long trackNumber = m.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER);
            long trackCount = m.getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS);

            Bundle bundle = new Bundle();
            bundle.putLong(MediaMetadataCompat.METADATA_KEY_DURATION,duration);

            MediaMetadata mediaMetadata = new MediaMetadata.Builder()
                    .setTitle(title)
                    .setDisplayTitle(displayTitle)
                    .setAlbumArtist(artist)
                    .setAlbumTitle(album)
                    .setComposer(composer)
                    .setTrackNumber((int) trackNumber)
                    .setTotalTrackCount((int) trackCount)
                    .setWriter(writer)
                    .setArtworkUri(Uri.parse(albumArtUri))
                    .setExtras(bundle)
                    .build();

            MediaItem mediaItem = new MediaItem.Builder()
                    .setMediaId(audioUri)
                    .setUri(Uri.parse(audioUri))
                    .setMimeType(MimeTypes.AUDIO_MPEG)
                    .setMediaMetadata(mediaMetadata)
                    .build();
            mediaItemList.add(mediaItem);
        }
        return mediaItemList;
    }

    public static void savePlayingAudio(MediaDescriptionCompat description, long position) {
        SharedPreferences preferences = SPUtils.getPreferences();
        preferences.edit()
                .putString(SPUtils.SP_RECENT_AUDIO_ID, description.getMediaId())
                .putString(SPUtils.SP_RECENT_AUDIO_TITLE, description.getTitle()+"")
                .putLong(SPUtils.SP_RECENT_AUDIO_POSITION, position)
                .apply();
    }

}
